package com.zhucai.credit.bank.ccbe;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.SocketException;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.zhucai.credit.exception.SubmitCcbException;
import com.zhucai.credit.monitor.service.INotificationService;

/**
 * @author taojie
 * 建行外联客户端封装
 */
@Component
public class CcbeClient {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Value("${ccbe.client-ip}")
	private String clientIp;

	@Value("${ccbe.client-port}")
	private Integer clientPort;
	@Resource(name="SMS")
	private INotificationService iNotificationService;
	
	public String req(String request) throws IOException,SubmitCcbException{
		// 资源自动关闭
		try (Socket socket = new Socket(clientIp, clientPort);
				OutputStreamWriter os = new OutputStreamWriter(socket.getOutputStream(), "GB18030");
				BufferedWriter bw = new BufferedWriter(os);) {
			bw.write(request);
			bw.flush();
			// 资源自动关闭
			try (BufferedInputStream is = new BufferedInputStream(socket.getInputStream());
					BufferedReader br = new BufferedReader(new InputStreamReader(is, "GB18030"));) {
				StringBuilder sb = new StringBuilder();
				String line = null;
				while ((line = br.readLine()) != null) {
					sb.append("\r\n").append(line);
				}
				return sb.toString();
			}
		} catch (IOException e) {
			logger.error("请求建行E点通失败", e);
			iNotificationService.notification("### 建行网关异常");
			throw new SocketException();
		}catch (SubmitCcbException e) {
			logger.error("请求建行E点通失败", e);
			throw new SubmitCcbException("请求建行E点通失败",e);
		}

	}
}
